package com.ruoyi.common.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 客户端用户集
 *
 * @author ruoyi
 */
public class WebSocketUsers
{
    /**
     * WebSocketUsers 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class);

    /**
     * 用户集
     */
    private static Map<String, WebSocketSession> USERS = new ConcurrentHashMap();

    /**
     * 存储用户
     *
     * @param key 唯一键
     * @param session 用户信息
     */
    public static void put(String key, Session session, Long userId)
    {
        USERS.put(key, new WebSocketSession(userId, session));
    }

    /**
     * 移出用户
     *
     * @param key 键
     */
    public static boolean remove(String key)
    {
        LOGGER.info("\n 正在移出用户 - {}", key);
        WebSocketSession remove = USERS.remove(key);
        if (remove != null)
        {
            boolean containsValue = USERS.containsValue(remove);
            LOGGER.info("\n 移出结果 - {}", containsValue ? "失败" : "成功");
            return containsValue;
        }
        else
        {
            return true;
        }
    }

    /**
     * 获取在线用户列表
     *
     * @return 返回用户集合
     */
    public static Map<String, WebSocketSession> getUsers()
    {
        return USERS;
    }

    /**
     * 群发消息文本消息
     *
     * @param message 消息内容
     */
    public static void sendMessageToUsersByText(String message)
    {
        Collection<WebSocketSession> values = USERS.values();
        for (WebSocketSession value : values)
        {
            sendMessageToUserByText(value.getSession(), message);
        }
    }

    /**
     * 发送文本消息
     *
     * @param session 用户session
     * @param message 消息内容
     */
    public static void sendMessageToUserByText(Session session, String message)
    {
        if (session != null)
        {
            try
            {
                session.getBasicRemote().sendText(message);
            }
            catch (IOException e)
            {
                LOGGER.error("\n[发送消息异常]", e);
            }
        }
        else
        {
            LOGGER.info("\n[你已离线]");
        }
    }

    /**
     * 发送文本消息
     *
     * @param userId  用户id
     * @param message 消息内容
     */
    public static void sendMessageToUserByUserId(Long userId, String message) {

        Map<String, WebSocketSession> users = getUsers();

        for(String key : users.keySet()) {
            WebSocketSession webSocketSession = users.get(key);

            if(webSocketSession.getUserId().equals(userId)) {
                sendMessageToUserByText(webSocketSession.getSession(), message);
            }
        }
    }

    private static class WebSocketSession {

        private Long userId;

        private Session session;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            WebSocketSession that = (WebSocketSession) o;
            return Objects.equals(userId, that.userId) && Objects.equals(session, that.session);
        }

        @Override
        public int hashCode() {
            return Objects.hash(userId, session);
        }

        public WebSocketSession(Long userId, Session session) {
            this.userId = userId;
            this.session = session;
        }

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }

        public Session getSession() {
            return session;
        }

        public void setSession(Session session) {
            this.session = session;
        }
    }
}
